const path = require('path')
const fs = require('fs')
const { v4: uuidv4 } = require('uuid')
const os = require('os')

function getIPAddress() {
  const networkInterfaces = os.networkInterfaces()
  if (!networkInterfaces) {
    return '127.0.0.1'
  }

  for (const name of Object.keys(networkInterfaces)) {
    const interfaces = networkInterfaces[name]
    if (!interfaces) {
      continue
    }

    for (const net of interfaces) {
      // 过滤出IPv4非loopback地址
      if (net && net.family === 'IPv4' && !net.internal) {
        return net.address
      }
    }
  }
  return '127.0.0.1' // 如果没有找到合适的IP，返回localhost
}
const ipAddress = getIPAddress()
const port = process.env.PORT || 2230

class FileService {
  constructor() {
    this.uploadDir = path.join(__dirname, '../public/uploads')
    // 确保上传目录存在
    if (!fs.existsSync(this.uploadDir)) {
      fs.mkdirSync(this.uploadDir, { recursive: true })
    }
  }

  async saveFile(file) {
    try {
      const fileId = uuidv4()
      // 对原始文件名进行解码，确保中文等字符正确显示
      const originalName = Buffer.from(file.originalname, 'binary').toString('utf8')
      const extension = path.extname(originalName)
      const fileName = `${fileId}${extension}`
      const filePath = path.join(this.uploadDir, fileName)

      // 将文件保存到服务器
      await fs.promises.writeFile(filePath, file.buffer)

      // 构建文件访问URL
      const fileUrl = `/uploads/${fileName}`

      return {
        id: fileId,
        name: originalName,
        url: fileUrl,
        fullPath: `http://${ipAddress}:${port}` + fileUrl,
      }
    } catch (error) {
      throw new Error(`文件保存失败: ${error.message}`)
    }
  }

  async deleteFile(fileId) {
    try {
      const files = await fs.promises.readdir(this.uploadDir)
      const targetFile = files.find((file) => file.startsWith(fileId))

      if (targetFile) {
        await fs.promises.unlink(path.join(this.uploadDir, targetFile))
        return true
      }
      return false
    } catch (error) {
      throw new Error(`文件删除失败: ${error.message}`)
    }
  }
}

module.exports = new FileService()
